<!-- 系统信息页面 -->
<template>
  <div class="system-info-container">
    <n-card title="系统信息" class="system-card">
      <template #header-extra>
        <n-button @click="refreshInfo" type="primary" size="small">
          <template #icon><n-icon><RefreshOutline /></n-icon></template>
          刷新
        </n-button>
      </template>
      
      <n-spin :show="loading">
        <n-tabs type="line">
          <!-- 基本信息 -->
          <n-tab-pane name="basic" tab="基本信息">
            <n-descriptions bordered>
              <n-descriptions-item label="操作系统">
                {{ systemInfo.type }} {{ systemInfo.release }}
              </n-descriptions-item>
              <n-descriptions-item label="平台">
                {{ systemInfo.platform }}
              </n-descriptions-item>
              <n-descriptions-item label="架构">
                {{ systemInfo.arch }}
              </n-descriptions-item>
              <n-descriptions-item label="主机名">
                {{ systemInfo.hostname }}
              </n-descriptions-item>
              <n-descriptions-item label="运行时间">
                {{ formatUptime(systemInfo.uptime) }}
              </n-descriptions-item>
            </n-descriptions>
          </n-tab-pane>
          
          <!-- CPU信息 -->
          <n-tab-pane name="cpu" tab="CPU信息">
            <n-descriptions bordered>
              <n-descriptions-item label="CPU型号">
                {{ cpuInfo.model || 'N/A' }}
              </n-descriptions-item>
              <n-descriptions-item label="CPU核心数">
                {{ cpuInfo.cpuCount || 0 }}
              </n-descriptions-item>
              <n-descriptions-item label="CPU频率">
                {{ cpuInfo.speed || 0 }} MHz
              </n-descriptions-item>
              <n-descriptions-item label="平均负载">
                {{ cpuInfo.loadAvg?.join(' / ') || 'N/A' }}
              </n-descriptions-item>
            </n-descriptions>
            
            <div class="chart-container">
              <h3>CPU使用率</h3>
              <n-progress type="line" :percentage="cpuUsagePercent" :color="cpuUsageColor" />
            </div>
          </n-tab-pane>
          
          <!-- 内存信息 -->
          <n-tab-pane name="memory" tab="内存信息">
            <n-descriptions bordered>
              <n-descriptions-item label="总内存">
                {{ formatBytes(memoryInfo.totalMemory || 0) }}
              </n-descriptions-item>
              <n-descriptions-item label="已用内存">
                {{ formatBytes(memoryInfo.usedMemory || 0) }}
              </n-descriptions-item>
              <n-descriptions-item label="剩余内存">
                {{ formatBytes(memoryInfo.freeMemory || 0) }}
              </n-descriptions-item>
            </n-descriptions>
            
            <div class="chart-container">
              <h3>内存使用率: {{ (memoryInfo.usedPercent || 0).toFixed(1) }}%</h3>
              <n-progress 
                type="line" 
                :percentage="memoryInfo.usedPercent || 0" 
                :indicator-placement="'inside'"
              />
            </div>
          </n-tab-pane>
          
          <!-- 磁盘信息 -->
          <n-tab-pane name="disk" tab="磁盘信息">
            <n-input 
              type="textarea" 
              :value="diskInfo.data || ''" 
              :autosize="{ minRows: 10, maxRows: 20 }" 
              readonly 
            />
          </n-tab-pane>
          
          <!-- 应用信息 -->
          <n-tab-pane name="app" tab="应用信息">
            <n-descriptions bordered>
              <n-descriptions-item label="应用名称">
                {{ appInfo.name }}
              </n-descriptions-item>
              <n-descriptions-item label="应用版本">
                {{ appInfo.version }}
              </n-descriptions-item>
              <n-descriptions-item label="应用路径">
                {{ appInfo.appPath }}
              </n-descriptions-item>
              <n-descriptions-item label="本地化">
                {{ appInfo.locale }}
              </n-descriptions-item>
              <n-descriptions-item label="打包状态">
                {{ appInfo.isPackaged ? '已打包' : '开发模式' }}
              </n-descriptions-item>
            </n-descriptions>
          </n-tab-pane>
        </n-tabs>
      </n-spin>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { 
  NCard, NButton, NIcon, NTabs, NTabPane, NDescriptions, 
  NDescriptionsItem, NSpin, NProgress, NInput 
} from 'naive-ui'
import { RefreshOutline } from '@vicons/ionicons5'
import { systemIPC } from '@utils/ipcModules'
import { appIPC } from '@utils/ipcModules'

// 定义类型
interface SystemInfo {
  platform: string
  arch: string
  cpus: any[]
  totalMemory: number
  freeMemory: number
  uptime: number
  hostname: string
  userInfo: any
  release: string
  type: string
  networkInterfaces: any
}

interface CpuInfo {
  success: boolean
  cpuCount?: number
  loadAvg?: number[]
  model?: string
  speed?: number
  error?: string
}

interface MemoryInfo {
  success: boolean
  totalMemory?: number
  freeMemory?: number
  usedMemory?: number
  usedPercent?: number
  processMemory?: any
  error?: string
}

interface DiskInfo {
  success: boolean
  data?: string
  error?: string
}

interface AppInfo {
  version: string
  name: string
  appPath: string
  locale: string
  isPackaged: boolean
  platform: string
  arch: string
  osVersion: string
  osName: string
}

// 状态
const loading = ref(false)
const systemInfo = ref<SystemInfo>({
  platform: '',
  arch: '',
  cpus: [],
  totalMemory: 0,
  freeMemory: 0,
  uptime: 0,
  hostname: '',
  userInfo: {},
  release: '',
  type: '',
  networkInterfaces: {}
})

const cpuInfo = ref<CpuInfo>({
  success: false
})

const memoryInfo = ref<MemoryInfo>({
  success: false
})

const diskInfo = ref<DiskInfo>({
  success: false,
  data: ''
})

const appInfo = ref<AppInfo>({
  version: '',
  name: '',
  appPath: '',
  locale: '',
  isPackaged: false,
  platform: '',
  arch: '',
  osVersion: '',
  osName: ''
})

// 计算属性
const cpuUsagePercent = computed(() => {
  // 这只是一个粗略的估计，实际上需要更复杂的计算
  if (!cpuInfo.value.loadAvg || cpuInfo.value.loadAvg.length === 0 || !cpuInfo.value.cpuCount) return 0
  return Math.min(cpuInfo.value.loadAvg[0] * 100 / cpuInfo.value.cpuCount, 100)
})

const cpuUsageColor = computed(() => {
  const percent = cpuUsagePercent.value
  if (percent < 50) return '#18a058'
  if (percent < 80) return '#f0a020'
  return '#d03050'
})

// 方法
async function fetchSystemInfo() {
  loading.value = true
  try {
    // 获取系统信息
    const sysInfo = await systemIPC.getSystemInfo()
    systemInfo.value = sysInfo as SystemInfo
    
    // 获取CPU信息
    const cpuResult = await systemIPC.getCpuUsage()
    if (cpuResult.success) {
      cpuInfo.value = cpuResult
    }
    
    // 获取内存信息
    const memoryResult = await systemIPC.getMemoryUsage()
    if (memoryResult.success) {
      memoryInfo.value = memoryResult
    }
    
    // 获取磁盘信息
    const diskResult = await systemIPC.getDiskInfo()
    if (diskResult.success) {
      diskInfo.value = diskResult
    }
    
    // 获取应用信息
    const app = await appIPC.getAppInfo()
    appInfo.value = app as AppInfo
  } catch (error) {
    console.error('获取系统信息失败:', error)
  } finally {
    loading.value = false
  }
}

function refreshInfo() {
  fetchSystemInfo()
}

// 格式化工具
function formatUptime(seconds: number): string {
  if (!seconds) return 'N/A'
  
  const days = Math.floor(seconds / (3600 * 24))
  const hours = Math.floor((seconds % (3600 * 24)) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  let result = ''
  if (days > 0) result += `${days}天 `
  if (hours > 0 || days > 0) result += `${hours}小时 `
  result += `${minutes}分钟`
  
  return result
}

function formatBytes(bytes: number): string {
  if (!bytes) return '0 B'
  
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let i = 0
  
  while (bytes >= 1024 && i < units.length - 1) {
    bytes /= 1024
    i++
  }
  
  return `${bytes.toFixed(2)} ${units[i]}`
}

// 生命周期
onMounted(() => {
  fetchSystemInfo()
})
</script>

<style scoped>
.system-info-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.system-card {
  max-width: 1200px;
  margin: 0 auto;
}

.chart-container {
  margin-top: 24px;
  padding: 16px;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.02);
}

.chart-container h3 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 500;
}
</style> 